<template>
  <div class="container">
    <headerBar :title="local.drafts" @changeLan="changeLan" :isNoReturn="true"></headerBar>
    <div class="all" :style="{paddingTop: pdt+'px'}">
      <!-- <div class="page__bd" style="width: 100%;">
        <div class="weui-search-bar">
          <div class="weui-search-bar__form">
            <div class="weui-search-bar__box">
              <icon class="weui-icon-search_in-box" type="search" size="14"></icon>
              <input
                type="text"
                class="weui-search-bar__input"
                :placeholder="local.searchStockCode"
                v-model="inputVal"
                :focus="inputShowed"
                @input="inputTyping"
              />
              <div class="weui-icon-clear" v-if="inputVal.length > 0" @click="clearInput">
                <icon type="clear" size="14"></icon>
              </div>
            </div>
            <label class="weui-search-bar__label" :hidden="inputShowed" @click="showInput">
              <icon class="weui-icon-search" type="search" size="14"></icon>
              <div class="weui-search-bar__text">{{local.search}}</div>
            </label>
          </div>
          <div
            class="weui-search-bar__cancel-btn"
            :hidden="!inputShowed"
            @click="hideInput"
          >{{local.cancel}}</div>
        </div>
        <div class="weui-cells searchbar-result" v-if="inputVal.length > 0"></div>
      </div>-->
      <div class="page__bd" style="width: 100%;">
        <div class="weui-search-bar">
          <div class="weui-search-bar__form">
            <div class="weui-search-bar__box">
              <input
                type="search"
                class="weui-search-bar__input"
                v-model="inputVal"
                :placeholder="local.searchStockCode"
                @blur="inputTyping"
              />
              <div class="weui-icon-clear" v-if="inputVal.length > 0" @click="clearInput">
                <icon type="clear" size="14"></icon>
              </div>
              <span
                style=";position:absolute;right: 11px;bottom: 2px;"
                :hidden="!inputShowed"
                @click="hideInput"
              ></span>
            </div>
            <label class="weui-search-bar__label" :hidden="inputShowed" @click="showInput">
              <icon class="weui-icon-search" type="search" size="14"></icon>
              <div class="weui-search-bar__text">{{local.search}}</div>
            </label>
          </div>
          <div
            class="weui-search-bar__cancel-btn"
            :hidden="!inputShowed"
            @click="inputTyping"
          >{{local.search}}</div>
        </div>
      </div>
      <div class="filter">
        <div class="filter-left">
          <div>{{local.screen}}：</div>
          <div @click="openDialogRight">{{local.time}}</div>
          <div>|</div>
          <div @click="openDialogRight">{{local.supplier}}</div>
        </div>
        <div class="clear-filter" @click="clearChoose">{{local.clearfilter}}</div>
      </div>
      <div class="cart">
        <template v-if="listData.length == 0">
          <div class="stock-in-record nodata-wrap">
            <img src="/static/style/block.png" class="nodata-img" />
            <p class="nodata-txt">{{local.nodata}}</p>
          </div>
        </template>
        <div v-else class="cartlist">
          <!-- 获得后台加入购物车的列表 -->
          <div
            class="item"
            @touchstart="startMove"
            @touchmove="deleteGoods"
            :data-index="index"
            v-for="(item,index) in listData"
            :key="index"
          >
            <div class="con" :style="item.textStyle">
              <!-- 获得后台加入购物车的列表 -->
              <div class="left">
                <!--左边的勾勾，图片，标题价格； -->
                <div
                  class="iconfont noselect-bg"
                  @click="changeColor(index,item.id)"
                  :class="[ Listids[index] ? 'iconselect icon-xianshi_xuanzetianchong' : '',{active:allcheck}]"
                ></div>
                <div
                  class="info"
                  @click="routerToUrl(`../../pages/stockInDetailsSubmit/index?id=${item.id}`)"
                >
                  <p class="model-name">{{local.stockInNo}}：{{item.code}}</p>
                  <p class="model-name">{{local.supplier}}：{{item.supplierName}}</p>
                  <p class="model-name">{{local.goodsName}}：{{item.goodsName}}</p>
                  <p class="model-name">{{local.warehouseIn}}：{{item.warehouseName}}</p>
                  <p class="model-name">{{local.submissionTime}}：{{item.createTime}}</p>
                </div>
              </div>
            </div>
            <!--向左滑动删除-->
            <div @click="delGoods(item.id,index)" class="delete">
              <div>{{local.deletesingle}}</div>
            </div>
          </div>
        </div>
        <!--删除了-->
        <div v-if="false" class="nogoods">
          <img
            src="http://nos.netease.com/mailpub/hxm/yanxuan-wap/p/20150730/style/img/icon-normal/noCart-a8fe3f12e5.png"
            alt
          />
        </div>
        <!--固定在下面的条框-->
        <div class="fixed">
          <div @click="allCheck">
            <i :class="{'icon-xianshi_xuanzetianchong1':allcheck}" class="iconfont iconselect1"></i>
            <span class="text-all">{{local.selectAll}}({{isCheckedNumber}})</span>
          </div>
          <div class="right">
            <div class="delete-btn" @click="deteleDraftList()">{{local.deletesingle}}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="modalRight" v-if="modalFlagRight" catchtouchmove="true">
      <div style="width: 100%; height: 100%;" @click="modalFlagRight = false"></div>
      <div class="dialog">
        <div class="tip-name">{{local.stockInNo}}:</div>
        <input v-model="code" />
        <div class="tip-name">{{local.selectSupplier}}:</div>
        <input disabled @click="supplierHandler()" v-model="mydata.name" />
        <div class="tip-name">{{local.selectTime}}:</div>
        <picker
          class="weui-btn flex"
          mode="date"
          :value="date"
          start="1999-01-01"
          end="2099-01-01"
          @change="DateChange"
        >
          <input disabled v-model="startTimeFormat" />
        </picker>
        <div class="tip-name">-</div>
        <picker
          class="weui-btn flex"
          mode="date"
          :value="date"
          start="1999-01-01"
          end="2099-01-01"
          @change="DateChangeEnd"
        >
          <input disabled v-model="endTimeFormat" />
        </picker>
        <div class="btn">
          <div class="cancel-btn" @click="closeDialogRight">{{local.cancel}}</div>
          <div class="confirm-btn" @click="searchBytip()">{{local.confirm}}</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
// import { formatTime } from '@/utils/index'
import home from '@/api/home'
import headerBar from '@/components/headerBar'
import { formatDate } from '@/utils/index'
import { throttle } from '@/utils/throttle'
export default {
  components: {
    headerBar
  },
  onShow() {
    this.initLang()
    this.initMyData()
  },
  computed: {
    isCheckedNumber() {
      let number = 0
      for (let i = 0; i < this.Listids.length; i++) {
        if (this.Listids[i]) {
          number++
        }
      }
      if (number === this.listData.length && number !== 0) {
        this.allcheck = true
      } else {
        this.allcheck = false
      }
      return number
    },
    startTimeFormat(){
      return this.startTime ? wx.$timeFormat(this.startTime) : '' // new Date(this.startTime).$format('dd/MM/yyyy') : ''
    },
    endTimeFormat(){
      return this.endTime ? wx.$timeFormat(this.endTime) : '' //new Date(this.endTime).$format('dd/MM/yyyy') : ''
    }
  },
  data() {
    return {
      supplierId: '',
      mydata: {
        id: '',
        name: ''
      },
      code: '',
      endTime: '',
      startTime: '',
      isBlock: false,
      local: wx.getStorageSync('local'),
      pdt: 66,
      modalFlag: false,
      istrue: false,
      date: '',
      inputShowed: false,
      inputVal: '',
      orderAddressId: '',
      allcheck: false,
      listData: [],
      numberlist: [],
      modellist: [],
      Listids: [],
      startX: '',
      moveX: '',
      X: 0,
      modalFlagRight: false
    }
  },
  methods: {
    initLang(){
      this.local = wx.getStorageSync('local')
    },
    supplierHandler() {
      // 跳转到 供应商列表
      wx.navigateTo({
        url: `../../pages/selectSupplier/index?name=supplier`
      })
    },
    initMyData() {
      var pages = getCurrentPages()
      var currPage = pages[pages.length - 1] //当前页面
      let myData = currPage.data.mydata
      this.mydata.id = myData ? myData.id : ''
      this.mydata.name = myData ? myData.name : ''
      this.supplierId = myData ? myData.id : ''
    },
    // 清空搜索条件
    clearChoose() {
      this.startTime = ''
      this.endTime = ''
      this.code = ''
      this.supplierId = ''
      this.getDraftList()
    },
    openDialogRight() {
      this.modalFlagRight = true
    },
    closeDialogRight() {
      this.modalFlagRight = false
    },
    async searchBytip() {
      wx.showLoading({title: this.local.loading})
      // 这里面是查询, 供应商选择需要跳转到新的客户选择
      home.getDraftList({
        code: this.code,
        'params[startTime]': this.startTime,
        'params[endTime]': this.endTime,
        supplierId: this.mydata.id
      }).then(res => {
        wx.hideLoading()
        const { rows, code, msg } = res
        this.modalFlagRight = false
        if (code !== 0) {
          wx.showToast({
            title: msg || 'error',
            icon: 'none',
            duration: 2000
          })
          return
        }
        rows.forEach(item=>{
          const {createTime} = item
          item.createTime = wx.$timeFormat(createTime,'time') //new Date(createTime).$format('dd/MM/yyyy hh:ss')
        })
        this.listData = rows
      })
    },
    changeLan(val) {
      this.local = val
    },
    // 批量删除
    async deteleDraftList() {
      let c = this.Listids.filter(str => {
        return !!str
      }).join()
      wx.showLoading({
        title: `${this.local.deleting}`
      })
      this.gotoPage(c)
    },
    gotoPage: throttle(
      0,
      false,
      function(c) {
        this._func(c)
      },
      false
    ),
    _func(c) {
      home.deteleDraftListBatch({ ids: c }).then((data) => {
        wx.hideLoading()
        wx.showToast({
          title: data.msg,
          duration: 4000,
          icon: 'none'
        })
        if (data.code == 0) {
          this.initTextStyle()
          this.getDraftList()
          this.Listids = []
        }
      })
    },
    // 获取草稿箱的列表
    async getDraftList() {
      wx.showLoading({title: this.local.loading})
      home.getDraftList({
        code: this.code,
        'params[startTime]': this.startTime,
        'params[endTime]': this.endTime,
        supplierId: this.supplierId
      }).then(res => {
        wx.hideLoading()
        const { rows, code, msg } = res
        this.modalFlagRight = false
        if (code !== 0) {
          wx.showToast({
            title: msg || 'error',
            icon: 'none',
            duration: 2000
          })
          return
        }
        rows.forEach(item=>{
          const {createTime} = item
          item.createTime = wx.$timeFormat(createTime,'time') //new Date(createTime).$format('dd/MM/yyyy hh:ss')
        })
        this.listData = rows
        this.initTextStyle()
      })
    },
    openDialog() {
      this.modalFlag = true
    },
    closeDialog() {
      this.modalFlag = false
    },
    routerToUrl(url) {
      wx.navigateTo({
        url
      })
    },
    DateChange(e) {
      this.startTime = e.mp.detail.value
    },
    DateChangeEnd(e) {
      this.endTime = e.mp.detail.value
    },
    async delGoods(id, index) {
      wx.showModal({
        title: '',
        content: '是否要删除该草稿',
        success: res => {
          if (res.confirm) {
            // 这里主要是删除的接口
            this.deleteCart(id, index)
          } else if (res.cancel) {
            // 滑动之前先初始化样式数据
            this.initTextStyle()
          }
        }
      })
    },
    // 单个删除
    async deleteCart(id, index) {
      const data = await home.deteleDraftListSingle({ id: id })
      wx.showToast({
        title: data.msg,
        duration: 4000,
        icon: 'none'
      })
      if (data.code == 0) {
        this.initTextStyle()
        this.getDraftList()
      }
    },
    initTextStyle() {
      // 滑动之前先初始化数据
      this.listData.map(item => {
        item.textStyle = ''
        item.number = 1
      })
    },
    startMove(e) {
      this.startX = e.touches[0].pageX
    },
    deleteGoods(e) {
      // 滑动之前先初始化样式数据
      this.initTextStyle()
      var index = e.currentTarget.dataset.index
      this.moveX = e.touches[0].pageX
      this.X = this.moveX - this.startX
      if (this.X >= 80 || this.X >= -80) {
        this.X = 0
      }
      if (this.X <= -80) {
        this.X = -160
      }
      this.listData[index].textStyle = `transform:translateX(${this.X}rpx);`
    },
    changeColor(index, id) {
      if (this.Listids[index]) {
        this.$set(this.Listids, index, false)
      } else {
        this.$set(this.Listids, index, id)
      }
    },
    allCheck() {
      // 先清空
      this.Listids = []
      if (this.allcheck) {
        this.allcheck = false
      } else {
        this.allcheck = true
        // 循环遍历所有的商品id
        for (let i = 0; i < this.listData.length; i++) {
          const element = this.listData[i]
          this.Listids.push(element.id)
        }
      }
    },
    showInput() {
      this.inputShowed = true
    },
    hideInput() {
      this.inputVal = ''
      this.inputShowed = false
    },
    clearInput() {
      this.inputVal = ''
    },
    inputTyping(e) {
    //  this.inputVal = e.mp.detail.value
      this.code = this.inputVal
      this.searchBytip()
    },
    initData(){
      // var myDate = new Date()
      // this.startTime = formatDate(myDate, 'YYYY-MM-DD')
      // this.endTime = formatDate(myDate, 'YYYY-MM-DD')
    }
  },
  onLoad() {
    this.initLang()
    this.initData()
    this.pdt = this.globalData.CustomBar
    this.getDraftList()
  },
  created() {}
}
</script>

<style scoped lang="scss">
@import 'index';
page {
  background-color: #ffffff;
  z-index: 999;
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  background: rgba(0, 0, 0, 0.5);
  text-align: center;
  /*position: fixed;*/
  align-items: center;
  justify-content: center;
}
.weui-demo-dialog {
  visibility: hidden;
  opacity: 0;
  transition: opacity 0.3s;
}
.weui-demo-dialog_show {
  visibility: visible;
  opacity: 1;
}
.log-list {
  display: flex;
  flex-direction: column;
  padding: 40rpx;
}

.log-item {
  margin: 10rpx;
}
.searchbar-result {
  margin-top: 0;
  font-size: 14px;
}
.searchbar-result:before {
  display: none;
}
.weui-cell {
  padding: 12px 15px 12px 35px;
}
</style>
